package com.shxy.rlzy.controller;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shxy.rlzy.common.lang.Result;
import com.shxy.rlzy.entity.EmployeeInfo;
import com.shxy.rlzy.service.IEmployeeInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tanhao
 * @since 2021-09-23
 */
@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeInfoController extends BaseController {
    private IEmployeeInfoService employeeInfoService;
    @Autowired
    public void setEmployeeInfoService(IEmployeeInfoService employeeInfoService) {
        this.employeeInfoService = employeeInfoService;
    }

    /**
     * 获取员工列表
     * @param departId
     * @param current
     * @param size
     * @return
     */
    @GetMapping(value = {"/list/{departId}/{current}/{size}", "/list/{current}/{size}", "/list"})
    public Result list(@PathVariable Long departId, @PathVariable Integer current, @PathVariable Integer size) {
        QueryWrapper<EmployeeInfo> qw = new QueryWrapper<>();
        // 不查询被删除的员工
        qw.ne("statu", -1);
        // 如果部门编号大于0，则查询指定部门的员工
        if(departId > 0) {
            qw.eq("depart_id", departId);
        }
        // 分页查询员工列表
        Page<EmployeeInfo> page = employeeInfoService.page(new Page<>(current, size), qw);
        JSONObject rs = JSONUtil.createObj();
        rs.set("records", page.getRecords());
        rs.set("total", page.getTotal());
        rs.set("current", page.getCurrent());
        rs.set("size", page.getSize());
        return Result.succ(rs);
    }

    /**
     * 保存员工信息
     * @param employeeInfo
     * @return
     */
    @PutMapping("/save")
    @PreAuthorize("hasAuthority('emp:employee:save')")
    public Result save(@RequestBody @Validated EmployeeInfo employeeInfo) {
        // 检查手机号是否已注册
        if(employeeInfoService.phoneExist(employeeInfo.getId(), employeeInfo.getPhone())){
            return Result.fail("该手机已存在");
        }

        // 检查身份证号码是否已存在
        if(employeeInfoService.idCardExist(employeeInfo.getId(), employeeInfo.getIdCard())) {
            return Result.fail("该身份证已存在");
        }

        if(employeeInfoService.saveOrUpdate(employeeInfo)) {
            return Result.succ("员工信息保存成功");
        }

        return Result.fail("员工信息保存失败");
    }

    /**
     * 上传照片
     * @param file
     * @return
     */
    @PostMapping("/upload/photo")
    public Result uploadPic(MultipartFile file) {
        log.info(file.toString());
        return Result.succ();
    }

    /**
     * 根据编号删除用户信息
     * @param employeeId
     * @return
     */
    @DeleteMapping("/delete/{employeeId}")
    @PreAuthorize("hasAuthority('emp:employee:delete')")
    public Result deleteById(@PathVariable Long employeeId) {
        // 1、如果用户不存在
        EmployeeInfo employee = employeeInfoService.getById(employeeId);
        if(employee == null) {
            return Result.fail("要删除的员工不存在");
        }

        // 2、删除用户
        if(employeeInfoService.delete(employee)) {
            return Result.succ("删除成功");
        }
        return Result.fail("删除失败!");
    }

    /**
     * 导入员工信息
     * @param employees
     * @return
     */
    @PutMapping("/import")
    @PreAuthorize("hasAuthority('emp:employee:import')")
    public Result importEmployees(@RequestBody @Validated List<EmployeeInfo> employees) {
        // 0、去除重复员工：身份证和电话唯一
        employees = employees.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(EmployeeInfo::getIdCard))), ArrayList::new));
        employees = employees.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(EmployeeInfo::getPhone))), ArrayList::new));
        // 1、判断导入的用户身份证号是否存在，若存在，则返回错误
        StringBuilder errors = new StringBuilder();
        employees.forEach(employeeInfo -> {
            if(employeeInfoService.idCardExist(null, employeeInfo.getIdCard())) {
                errors.append(String.format("%s(%s)-重复。", employeeInfo.getName(), employeeInfo.getIdCard()));
            }
        });
        if(!errors.isEmpty()) {
            return Result.fail(errors.toString());
        }

        // 2、批量保存用户信息
        employeeInfoService.saveBatch(employees);

        return Result.succ(String.format("成功导入%d条记录。", employees.size()));
    }
}
